%Main function to recognize text from a single text image
function [ recText ] = recognizeText(handles, image, models, isLADA, letterArea, imageContent,cid,cursorAngle )


    %Saves binary image to txt file, 0s are written as space character and
    %1s are written as 8s.
    function saveMatrixToFile(matrix)
        filenr=fopen('bin.txt','w');
        for i = 1 : size(binaryIm, 1)
            for j = 1 : size(binaryIm, 2)
                if binaryIm(i,j) == 1
                    fprintf(filenr,'8',binaryIm(i,:));
                else
                    fprintf(filenr,' ',binaryIm(i,:));
                end
            end
            fprintf(filenr,'\n');
        end
        fclose(filenr);
    end

    %Read image
    img = imread(image);
    %Convert to binary image (threshold value is default 40)
    img = threshold2Bin( img );
    
    %Get the boundary box which contains the actual text, cropping the
    %background part
    [ nlines topRow bottomRow leftColumn rightColumn ] = lineBoundaries( img );
    
    %Write the binary image to a file to check the column numbers manually
    %ie where the letters start and end, is there any overlap in neighbor
    %letters
    %saveMatrixToFile(img);
    
    %Until we reach the end of the image, continue exhaustively to detect
    %letters
    %Start searching the new letter from the leftmost column
    newLetterStartColumn = 1;
    %Count the letter index starting from 1 and ending is indefinite atm
    index = 1;
    %Get the number of different HMM models 
    nmodels = size(models,2);
    recText = cell(nmodels,2);
    
    %Get the HMM and cluster data
    clusterCenters = getappdata(handles.figure1, 'clusterCenters');
    normalizationFactors = getappdata(handles.figure1, 'normalizationFactors');
    priorProb = getappdata(handles.figure1, 'priorProb');
    obsProb = getappdata(handles.figure1, 'obsProb');
    transProb = getappdata(handles.figure1, 'transProb');
    
    %Iterate through the lines, finding letters and recognizing them
    for currentLine = 1 : nlines
        while 1
            %Get the new letter boundary
            [rminLetter, rmaxLetter, cminLetter, cmaxLetter] = bboxletter(img, newLetterStartColumn);
            %If there are no letters left
            if cminLetter == -1
                break;
            end
            %Indicate the boundary box in the image itself
            drawLetterAreaIndicators (handles,'Yellow',rmin + rminLetter, rmin + rmaxLetter, cmin + cminLetter, cmin + cmaxLetter);
            %Make the observations specified by the current model
            %0 means we are in recognition mode, not training. And the next
            %parameter is only relevant in training mode
            observations = letterObservations( currentLetter, models, handles, 0, ~ );
            %observations = count_segments(img((rmin+rminLetter) : (rmin+rmaxLetter), (cmin+cminLetter):(cmin+cmaxLetter)),0);
            
            %Check the likelihood of each HMM model

            for i= 1 : nmodels
                observations{i}
                %Convert raw observations to clusters using the previous
                %data gathered during training
                %First normalize the data
                normalizedObs = observations{i}./repmat(normalizationFactors{i},size(observations{i},1));
                obsClusters = getCluster(clusterCenters{i} , normalizedObs);
                for j = 1 : size(priorProb, 2)
                    loglik(i,j) = dhmm_logprob(obsClusters, priorProb{i,j}, transProb{i,j}, obsProb{i,j});
                    matlablik(i,j) =  hmmdecode(obsClusters, transProb{i,j}, obsProb{i,j});
                    appendStatus(handles, sprintf('[Tool] Model %s Log likelihood letter is %c : %.2f', models{i}.name, char(64+j), loglik(i,j)));
                    appendStatus(handles, sprintf('[MATLAB] Model %s Log likelihood letter is %c : %.2f', models{i}.name, char(64+j), matlablik(i,j)));
                end
                %Find which letter was most probable
                [C,I] = max(loglik(i));
                [C2, I2] = max(matlablik(i));
                %If most probable candidate has -Inf likelihood then recognition
                %yielded no results
                if C == -Inf
                    recText{i,1} = [recText{i,1} '-'];
                    appendStatus(handles,sprintf('[Tool] Model %s : No suitable letter found for letter candidate %d', models{i}.name,index));
                else
                    recText{i,1} = [recText{i,1} char(64+I)];
                    appendStatus(handles,sprintf('[Tool] Model %s :Possible candidate for letter #%d is %c', models{i}.name, index, char(64+I)));
                end
                
                if C2 == -Inf
                    recText{i,2} = [recText{i,2} '-'];
                    appendStatus(handles,sprintf('[MATLAB] Model %s : No suitable letter found for letter candidate %d', models{i}.name,index));
                else
                    recText{i,2} = [recText{i,2} char(64+I2)];
                    appendStatus(handles,sprintf('[MATLAB] Model %s :Possible candidate for letter #%d is %c', models{i}.name, index, char(64+I2)));
                end
                
                
            end

            pause(0.5);

            %Set the search start column to where the previous letter ended
            newLetterStartColumn = cmaxLetter + 1;
            %Increment the letter count
            index = index + 1;
            %If the previous letter ended at the right border of the image
            %Or in other words if it was the last letter in the image
            if newLetterStartColumn > cmax
                break;
            end
        end
    end
end